package com.chang.cheng.toutiaoserver.login.service.impl;

import com.chang.cheng.toutiaoserver.login.service.ApUserSendSmsService;
import com.chang.cheng.toutiaoserver.model.common.dtos.ResponseResult;
import com.chang.cheng.toutiaoserver.model.common.enums.AppHttpCodeEnum;
import com.chang.cheng.toutiaoserver.model.user.pojos.AppUser;
import com.chang.cheng.toutiaoserver.utils.LocalDateUtil;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.context.ContextLoader;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * @Auther: asus
 * @Date: 2022/01/03 11:08
 * @Description:
 */
@Service
public class ApUserSendSmsServiceImpl  implements ApUserSendSmsService {
    @Override
    public ResponseResult sendSmsAppV1(Long mobile, HttpServletRequest request) {
        ServletContext servletContext = request.getServletContext();
        System.out.println(servletContext);
        //手机号码存入时间,到秒
        Long nowTime = LocalDateUtil.LDTToSecond();
        //先判断ServletContext域中是否有手机号码,是否隔了1分钟.
        String sMobile = String.valueOf(mobile);
        Object attribute = servletContext.getAttribute(sMobile);
        // 如果通过手机号获得的值为空或者比现在大60秒就符合
        //手机验证码间隔时间默认短一些0
        long intervalSecond= 0L;
        if (attribute!=null&& !Objects.equals(attribute.toString(), "")){
            // 值中是一个数组,前面是时间精确到秒,后面是验证码.
            String[] value=(String[])attribute;
            String preTime=value[0];//后面验证码取出方便后面验证
            intervalSecond= nowTime - Long.parseLong(preTime);
        }
        if(attribute==null|| Objects.equals(attribute.toString(), "") || intervalSecond >60){

            // TODO 短信发送模块, 返回的验证码returnCode存入数据库?ServletContext?
            int iCode = new Random().nextInt(1000001) - 1;
            //前面补0
            String sCode = String.format("%06d", iCode);
            //将时间和验证码存入ServletContext
            servletContext.setAttribute(sMobile, new String[]{nowTime.toString(), sCode});
            return ResponseResult.okResult(null);
        }
        // 如果能获取到手机验证码发送时间,并且小于60
        if(!Objects.equals(attribute.toString(), "") && intervalSecond <= 60){
            return ResponseResult.errorResult(AppHttpCodeEnum.SEND_VERIFICATION_CODE_FREQUENTLY);
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.VERIFICATION_CODE_ERROR);
    }

}
